package cn.exrick.xboot.file

import cn.exrick.xboot.core.common.utils.CommonUtil
import cn.exrick.xboot.core.common.utils.ResultUtil
import cn.exrick.xboot.core.common.vo.Result
import cn.exrick.xboot.core.vo.AliServiceSetting
import com.aliyun.oss.OSSClient
import com.aliyun.oss.common.auth.DefaultCredentialProvider
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import java.io.InputStream

@Service
class IFileServiceImpl : IFileService {


    override fun uploadFile(file: MultipartFile): Result<String?>? {

        return ResultUtil.data(aliInputStreamUpload(file.inputStream, CommonUtil.renamePic(file.originalFilename)))
    }


    private fun aliInputStreamUpload(inputStream: InputStream, key: String) : String? {

        val ossClient = OSSClient(AliServiceSetting().http + AliServiceSetting().endpoint, DefaultCredentialProvider(AliServiceSetting().accessKey, AliServiceSetting().secretKey),
                null)
        ossClient.putObject(AliServiceSetting().bucket, key, inputStream)
        ossClient.shutdown()
        return AliServiceSetting().http.plus(AliServiceSetting().bucket).plus(".").plus(AliServiceSetting().endpoint).plus("/").plus(key)
    }

}